const unless = require('koa-unless');
const { generateToken } = require('../helpers/jwt');

module.exports = (opts = {}) => {
    const {
        authorization = 'authorization',
        setAuthorization,
        tokenKey = 'user',
        passthrough,
        debug
    } = opts;

    const middleware = async function refreshToken(ctx, next) {
        const decodedToken = ctx.state[tokenKey];

        try {
            if (!decodedToken) {
                throw new Error('JWTToken not Found');
            }

            await next();

            const { id, username } = decodedToken;

            const ttl = await ctx.redis.ttl(`access_token:${username}`);

            if (ttl <= 10 * 60) {
                const token = generateToken({ id, username });
                if (setAuthorization && typeof setAuthorization === 'function') {
                    await setAuthorization(ctx, token);
                }
            }
        } catch (e) {
            if (!passthrough) {
                const msg = debug ? e.message : 'Refresh Token Error';
                ctx.throw(500, msg, { originalError: e });
            } else {
                // lets downstream middlewares handle JWT exceptions
                ctx.state.jwtOriginalError = e;
            }
        }
    };

    middleware.unless = unless;
    return middleware;
};
